package com.guiji.quartz.domain;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.task.DataSaveUtil;
import com.guiji.quartz.util.DelPicUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description: 需要代理
 * @author: wangxw
 * @date 2021/11/24 9:51
 */
public class EuronewsBusiness {
	private static final Logger log = LoggerFactory.getLogger(EuronewsBusiness.class);

	public static void mainMethod() throws Exception {
		HttpResponse response = null;
		try {
			response = HttpRequest.get("https://www.euronews.com/news/business")
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
				.header("Accept-Encoding", "gzip, deflate")
				.setHttpProxy(ProxyConfig.url, ProxyConfig.ip)
				.setConnectionTimeout(30000)
				.execute();

			if (null != response) {
				if (response.getStatus() == 200) {
					List<HttpCookie> cookies = response.getCookies();
					String resp = response.body();
					Set<String> resUrl = getUrl(resp);
					getContent(resUrl, cookies);
				} else {
					log.error("https://www.euronews.com/news/business " + String.valueOf(response.getStatus()));
				}
			} else {
				log.error("https://www.euronews.com/news/business " + String.valueOf(response.getStatus()));
			}

		} catch (Exception e) {
			log.error("访问 https://www.euronews.com/news/business 失败" + e);
			return;
		}


	}

	public static void setCookies(List<HttpCookie> cookies,String host) throws MalformedURLException, URISyntaxException {
		if (null != cookies && cookies.size() > 0) {
			CookieManager ccm = new CookieManager();
			CookieStore CookieStore = ccm.getCookieStore();
			for (HttpCookie cookie : cookies) {
				URL domain = new URL(host);
				CookieStore.add(domain.toURI(), cookie);
			}
			HttpRequest.setCookieManager(ccm);
		}
	}

	private static void getContent(Set<String> listContent, List<HttpCookie> cookies) throws MalformedURLException, URISyntaxException, InterruptedException {
		for (String url : listContent) {
			Thread.sleep(1000);
			if (!url.startsWith("https")) {
				url = new StringBuffer("https://www.euronews.com").append(url).toString();
			}

			setCookies(cookies,"https://www.euronews.com");

			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url).setHttpProxy(ProxyConfig.url, ProxyConfig.ip).setConnectionTimeout(15000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				title = (String) jxDocument.sel("//h1/text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			StringBuffer content = new StringBuffer();
			String contentStr = null;
			JXDocument jxDocumentP;
			Document document = null;
			try {

				document = Jsoup.parse(doc);
				Element mainArea = document.getElementsByClass("c-article-content c-article-content--next js-article-content ").get(0);
				Elements pElements = mainArea.select("P");
				if (null != pElements && pElements.size() > 0) {
					for (Element pdom : pElements) {
						jxDocumentP = new JXDocument(pdom.toString());
						String temp = jxDocumentP.sel("//text()").get(0).toString();
						if (null != temp && !temp.toString().contains("Your support through more subscriptions can help us") && !temp.toString().contains("Only the headline and picture of this report")) {
							content.append(temp + "$$$");
						}
					}
				}

				contentStr = content.toString();
			} catch (Exception e) {
				continue;
			}

			List<Object> srcImgs = new ArrayList<>();
			List<String> newImgs = new ArrayList<>();
			String img = null;
			try {
				int imgSize = jxDocument.sel("//div[@class='c-video-player__container']//img/@src").size();
				if (imgSize > 0) {
					String temp = null;
					for (int k = 0; k < imgSize; k++) {
						temp = jxDocument.sel("//div[@class='c-video-player__container']//img/@src").get(k).toString();
						img = temp.strip();
						srcImgs.add(img);
					}
				}

			} catch (Exception e) {
				log.error("可能没有图片");
				img = "";
			} finally {
				if (srcImgs.size() > 0) {
					newImgs = DelPicUtil.delPic(srcImgs);
				}
			}

			Date date = new Date();
			if (contentStr.length() > 50000 || contentStr.replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				System.out.println("=======================================================");
				System.out.println(url);
				System.out.println(title);

				for (Object imgitem : srcImgs) {
					System.out.println(" " + imgitem);
				}
				System.out.println(contentStr);
				System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
				DataSaveUtil.saveData(title, contentStr, newImgs, url, date, "https://www.euronews.com/news/business", "Euronews-EnglishBusiness");
				log.info(Thread.currentThread().getName() + "-----------------Euronews-EnglishBusiness----------------");
			} catch (Exception e) {
				continue;
			}

		}
	}

	private static Set<String> getUrl(String content) {

		Set<String> res = new HashSet<>();
		String pattern = "href=\"/next/[0-9]{4}/[0-9]{2}/.*?\"";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			String temp = m.group();
			temp = temp.replace("href=\"", "");
			temp = temp.replace("\"", "");
			res.add(temp);
		}
		return res;
	}


//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}

}


